package leets.leet2343;

import java.util.Arrays;
import java.util.Objects;

public class Solution {
    public int[] smallestTrimmedNumbers(String[] nums, int[][] queries) {
        int[][] temp=new int[nums[0].length()+1][nums.length+1];
        for (int[] a:temp){
            Arrays.fill(a,-1);
        }
        int[] res=new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int k=queries[i][0];

            int trim=queries[i][1];
            if(temp[trim][k]==-1){
                Pair<Integer,String>[] pairs=new Pair[nums.length];
                for (int j = 0; j < nums.length; j++) {
                    pairs[j]=new Pair<>(j,nums[j].substring(nums[j].length()-trim));
                }
                Arrays.sort(pairs, (o1, o2) -> {
                    if (!Objects.equals(o1.value, o2.value)) {
                        return o1.value.compareTo(o2.value);
                    } else {
                        return o1.key - o2.key;
                    }
                });
                for (int j = 1; j <= nums.length; j++) {
                    temp[trim][j]=pairs[j-1].key;
                }
            }
            res[i]=temp[trim][k];

        }
        return res;
    }
}
class Pair<K,V>{
    K key;
    V value;

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }
}